package com.xszx.system.controller;
import com.alibaba.fastjson.JSON;
import com.xszx.server.dto.AjaxJson;
import com.xszx.server.dto.LoginUserDto;
import com.xszx.server.dto.Page;
import com.xszx.server.entity.User;
import com.xszx.server.service.UserService;
import com.xszx.server.util.CopyUtil;
import com.xszx.server.util.UuidUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/getAllUsers")
    public Page getAllUsers(@RequestBody Page page){
        return userService.getAllUsers(page);
    }

    @GetMapping("/getUser")
    public AjaxJson getUser(String id){
        return AjaxJson.success().put("users",userService.getUser(id));
    }

    @PostMapping("/save")
    public AjaxJson save(@RequestBody User user){
        //进行后端的二次加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return AjaxJson.success(userService.saveOrUpdate(user));
    }

    @GetMapping("/deleteUser")
    public AjaxJson deleteUser(String id){
        int result = userService.del(id);
        if(result>0){
            return AjaxJson.success("删除成功");
        }else{
            return AjaxJson.error("删除失败");
        }
    }
    @PostMapping("/save-password")
    public AjaxJson savePassword(@RequestBody User user){
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        int result = userService.update(user);
        if(result>0){
            return AjaxJson.success("更新成功");
        }else{
            return AjaxJson.error("更新失败");
        }
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public AjaxJson login(@RequestBody User user, HttpServletRequest request){
        //进行登录验证
        User userDb =userService.login(user);
        //生成token
        String token = UuidUtil.getShortUuid();
        //将已有的属性拷贝到LoginUserDto中
        LoginUserDto loginUserDto = CopyUtil.copy(userDb,LoginUserDto.class);
        //设置token属性
        loginUserDto.setToken(token);
        //设置资源权限
        loginUserDto.setResources(userService.getResources(user.getId()));
        //将登录成功后的token存储起来
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUserDto), 1800, TimeUnit.SECONDS);
        return AjaxJson.success("登录成功").put("loginUser",loginUserDto);
    }

    /**
     * 用户退出登录
     * @param token
     * @return
     */
    @PostMapping("/logout/{token}")
    public AjaxJson logout(@PathVariable("token") String token){
        redisTemplate.delete(token);//将redis中的指定token删除
        return AjaxJson.success("退成登录成功");
    }
}
